package org.dromara.quickswing.ui;

import org.dromara.quickswing.ui.app.QSAction;

import javax.swing.*;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Jin
 */
public class QSActionRegistry {


    private final Map<String, Action> namedActions;

    public QSActionRegistry() {
        namedActions = new HashMap<>();
    }

    public void addAction(String key, Action action) {
        if (action == null) {
            throw new NullPointerException("action cannot be null");
        } else if (key == null) {
            throw new NullPointerException("key cannot be null");
        }
        namedActions.put(key, action);
    }

    public Action getAction(String key) {
        return namedActions.get(key);
    }

    public void fillAllActionMap(ActionMap actionMap) {
        for (Action action : namedActions.values()) {
            if (action instanceof QSAction<?> ) {
                String key = ((QSAction<?>) action).getKey();
                actionMap.put(key, action);
            }
        }
    }

    public void fillAllInputMap(InputMap inputMap) {
        for (Action action : namedActions.values()) {
            if (action instanceof QSAction<?>) {
                KeyStroke keyStroke = ((QSAction<?>) action).getKeyStroke();
                if (keyStroke != null) {
                    inputMap.put(keyStroke, ((QSAction<?>) action).getKey());
                }
            }
        }
    }

    public void fillActionMap(String key, ActionMap actionMap) {
        Action action = namedActions.get(key);
        if (action instanceof QSAction<?>) {
            actionMap.put(((QSAction<?>) action).getKey(), action);
        }
    }

    public void fillActionMap(QSAction<?> qsAction, ActionMap actionMap) {
        actionMap.put(qsAction.getKey(), qsAction);
    }

    public void fillInputMap(String key, InputMap inputMap) {
        Action action = namedActions.get(key);
        if (action instanceof QSAction<?> ) {
            KeyStroke keyStroke = ((QSAction<?>) action).getKeyStroke();
            if (keyStroke != null) {
                inputMap.put(keyStroke, ((QSAction<?>) action).getKey());
            }
        }
    }

    public void fillInputMap(QSAction<?> qsAction, InputMap inputMap) {
        KeyStroke keyStroke = qsAction.getKeyStroke();
        if (keyStroke != null) {
            inputMap.put(keyStroke, qsAction.getKey());
        }
    }

}